import config from '@/config'
import axios from 'axios'
import { Toast } from 'vant'
import { getToken } from '@/utils/auth'
import router from '@/router'

// 创建axios实例配置
const instance = axios.create({
    baseURL: config.baseApi,
    timeout: 1000 * 8
})

/**
* @description: 请求拦截器
* @author LoneWolf
*/
instance.interceptors.request.use(req => {
    const { headers } = req
    if (!headers['Content-Type']) {
        headers['Content-Type'] = 'application/json'
    }
    if (getToken()) {
        headers.Authorization = 'Bearer ' + getToken()
    }
    return req
}, err => {
    Toast.fail('请求超时')
    return Promise.reject(err)
})

/**
* @description: 响应拦截器
* @author LoneWolf
*/
instance.interceptors.response.use(res => {
    // 接口未返回code，直接返回数据
    const { data } = res
    const code = 200
    return { data, code }
}, err => {
    const { response } = err
    if (response) {
        const { status } = response
        if (status === 401) {
            Toast.fail('请登录')
            router.replace({
                path: '/login',
                query: { pre: encodeURIComponent(router.currentRoute.value.fullPath) }
            })
        } else if (status === 507) {
            Toast.fail('数据库错误')
        } else if (status === 400) {
            Toast.fail('请求参数错误')
        } else if (status === 409) {
            Toast.fail('此用户已举报过该文章')
        } else {
            Toast.fail('请求失败')
        }
    }
    return '请求失败'
})

/**
* axios请求核心函数
* @author LoneWolf
*/
const request = (url, options) => {
    if (options.method.toLowerCase() === 'get') options.params = options.data
    if (config.env === 'prod') {
        instance.defaults.baseURL = config.baseApi
    } else if (options.mock) {
        instance.defaults.baseURL = config.mockApi
    } else {
        instance.defaults.baseURL = config.mock ? config.mockApi : config.baseApi
    }
    return instance(url, options)
}

['get', 'post', 'put', 'delete', 'patch'].forEach(method => {
    request[method] = (url, options = {}) => {
        options.method = method
        return request(url, options)
    }
})

export default request
